
import mitt from 'mitt';  
export class WebSocketService {  
    private socket: WebSocket | null = null;  
    private url: string;  
    private emitter: any = mitt(); 
    
    constructor(url: string) {  
      this.url = url;  
    }  
    
    async connect() {  
      if (this.socket) {  
        this.socket.close();  
      }  
    
      this.socket = await new WebSocket(this.url);  
      if(!this.socket) {
        return false
      }
      this.socket.onopen = () => {  
        console.log('WebSocket 连接');  
      };  
    
      this.socket.onmessage = (event) => {  
        console.log('触发事件', event.data);  
        this.emitter.emit('message', event.data);  
        // 这里可以触发事件或更新 Vuex/Vue 3 的响应式状态  
      };  
    
      this.socket.onerror = (error) => {  
        console.log('WebSocket 错误 ', error);  
      };  
    
      this.socket.onclose = () => {  
        console.log('WebSocket 重新连接  ');  
        // 可以在这里尝试重新连接  
      };  
    }  
    
    send(data: any) {  
      if (this.socket && this.socket.readyState === WebSocket.OPEN) {  
        this.socket.send(data);  
      } else {  
        console.error('WebSocket 连接失败');  
      }  
    }  
    
    disconnect() {  
      console.log('WebSocket 退出连接  ');  
      if (this.socket) {  
        this.socket.close();  
        this.socket = null;  
      }  
    }  
    
    on(event: string, handler: Function) {  
      this.emitter.on(event, handler);  
    }  
    
    off(event: string, handler: Function) {  
      this.emitter.off(event, handler);  
    }  
    
  }